import axios from 'axios';
import qs from 'qs';
import { Loading, Message } from 'element-ui';
import router from '../router/index';

axios.defaults.timeout = 30000; //10000ms=10秒

let loadingInstance = null; //定义loading变量

//添加请求拦截器
axios.interceptors.request.use(
  (config) => {
    // config.baseURL = process.env.NODE_ENV == 'development' ? './api' : process.env.VUE_APP_API; //api
    if (config.url != 'auth/oauth/token') {
      //设置请求IP
      config.baseURL = 'http://62.234.3.184:8081'; //api
    }
    config.headers = {
      ...config.headers,
      timestamp: Math.round(new Date() / 1000),
    };

    if (config.headers['Content-Type'] != 'multipart/form-data') {
      // config.data = qs.stringify(config.data, { indices: true, allowDots: true });
    }
    loadingInstance = Loading.service({ fullscreen: true, text: '拼命请求中' });
    return config; //在发送请求之前做某事
  },
  (error) => {
    if (error) {
      loadingInstance?.close();
    }
    return Promise.reject(error);
  }
);

//添加响应拦截器
axios.interceptors.response.use(
  (response) => {
    loadingInstance?.close();
    if (response.data && response.data.code == 200) {
      return response.data;
    } else {
      // Message.warning({ message: response.data.msg });
      return response.data;
    }
  },
  (error) => {
    console.log('axios error', error.response);
    loadingInstance?.close();
    if (error && error.response) {
      //请求成功，500错误
      var resp = error.response;
      Message.warning({ message: resp.data.msg });
      if (error.response.status == 403) {
        //403,登陆失效
        router.push({ name: 'login' });
      }
      return { code: resp.status, data: null, msg: resp.data.msg };
    } else {
      //请求失败，404错误
      return { code: 999, data: '网络请求失败', msg: '网络请求失败' };
    }
  }
);

export default axios;
